// @Author EthanScriptOn
// @Desc
package config_source_loader

import (
	"gitee.com/fatzeng/srf_switch_config/config_define"
	"strconv"
	"strings"
)

type PropFileSourceLoader struct {
	*FileBaseSourceLoader
}

func (p *PropFileSourceLoader) Initialization() (err error) {
	keyValuePairsSlicing := GenerateSourceLoaderSlicing("=", true, 2)
	multiKeySlicing := GenerateSourceLoaderSlicing(".", true, -1)
	p.ConfigSourceLoaderSteps, err = GenerateAllowableCutFileBaseSourceLoaderSteps(p, keyValuePairsSlicing, multiKeySlicing, `(\\w+)\\[(\\d+)\\]`)
	if err != nil {
		return err
	}
	p.FileBaseSourceLoader, err = GenerateFileBaseSourceLoader(p, p.GetConfigSourceType())
	if err != nil {
		return err
	}
	return p.FileBaseSourceLoader.Initialization()
}

func (p *PropFileSourceLoader) SplitSegment(describes []*SegmentLineDescribe) ([]Segment, error) {
	segmentsMap := make(map[string][]*SegmentLineDescribe)
	for _, describe := range describes {
		for _, keyDescribe := range describe.multiKeySlice {
			if keyDescribe.level == 0 {
				segmentKey := keyDescribe.key + "-" + strconv.Itoa(keyDescribe.index)
				lineDescribes, ok := segmentsMap[segmentKey]
				if !ok {
					lineDescribes = make([]*SegmentLineDescribe, 0)
				}
				lineDescribes = append(lineDescribes, describe)
				segmentsMap[segmentKey] = lineDescribes
			}
		}
	}
	segments := make([]Segment, 0)
	for _, lineDescribes := range segmentsMap {
		segments = append(segments, lineDescribes)
	}
	return segments, nil
}

func (p *PropFileSourceLoader) IsAnnotation(line string) bool {
	return line == "" || strings.HasPrefix(line, "#")
}

func (p *PropFileSourceLoader) GetConfigSourceType() config_define.ConfigSourceType {
	return config_define.PROPERTIES
}
